package cn.edu.imust.loginregisterdemo.login.view;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.Bmob;
import cn.edu.imust.loginregisterdemo.R;
import cn.edu.imust.loginregisterdemo.base.BaseFragment;
import cn.edu.imust.loginregisterdemo.forgetpwd.ForgetPasswordActivity;
import cn.edu.imust.loginregisterdemo.register.view.RegisterActivity;
import cn.edu.imust.loginregisterdemo.utils.RectangleToCircleUtils;
import cn.edu.imust.loginregisterdemo.utils.Utils;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class LoginActivity extends AppCompatActivity {


    @BindView(R.id.iv_qq_login)
    ImageView ivQqLogin;                //qq
    @BindView(R.id.iv_weixin_login)
    ImageView ivWeixinLogin;            //微信
    @BindView(R.id.iv_weibo_login)
    ImageView ivWeiboLogin;             //微博
    @BindView(R.id.iv_head_img)
    ImageView iv_head_img;              //登录头像
    @BindView(R.id.btn_forget_pwd)
    TextView  btnForgetPwd;             //忘记密码
    @BindView(R.id.tv_toRegister)
    TextView  tvToRegister;             //注册
    @BindView(R.id.username_login)
    TextView  usernameLogin;            //用户名密码登录
    @BindView(R.id.sms_login)
    TextView  smsLogin;                  //手机验证码登录
    private SmsLoginFragment      smsLoginFragment;
    private UsernameLoginFragment usernameLoginFragment;
    private FragmentManager       fm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        ButterKnife.bind(this);
        Bmob.initialize(this, "33452dfaa0b4f1b9b1a5ea2c1818d5f4");
        LoginActivityPermissionsDispatcher.requestPermissionWithPermissionCheck(this);
        initView();
    }

    private void initView() {
        //初始化头像
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.head_image, null);
        Bitmap croppedBitmap = RectangleToCircleUtils.getCroppedBitmap(bitmap);
        iv_head_img.setImageBitmap(croppedBitmap);

        usernameLoginFragment = new UsernameLoginFragment();
        smsLoginFragment = new SmsLoginFragment();
        fm = getSupportFragmentManager();
        switchFragment(smsLoginFragment);

    }

    private void switchFragment(BaseFragment targetFragment) {
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.login_page_container, targetFragment);
        ft.commit();

    }

    @OnClick({R.id.btn_forget_pwd, R.id.tv_toRegister, R.id.username_login, R.id.sms_login, R.id.iv_qq_login, R.id.iv_weixin_login, R.id.iv_weibo_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_forget_pwd:
                startActivity(new Intent(this, ForgetPasswordActivity.class));
                break;
            case R.id.tv_toRegister:
                //跳转到注册界面
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                finish();               //销毁当前界面
                break;
            case R.id.username_login:   //账号密码登录
                switchFragment(usernameLoginFragment);
                break;
            case R.id.sms_login:        //手机验证码登录
                switchFragment(smsLoginFragment);
                break;
            case R.id.iv_qq_login:
                Utils.showSnackBar(this, view, "QQ登录");
                break;
            case R.id.iv_weixin_login:
                Utils.showSnackBar(this, view, "微信登录");
                break;
            case R.id.iv_weibo_login:
                Utils.showSnackBar(this, view, "微博登录");
                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LoginActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    /**
     * 只有全部成功时，才会调用
     */
    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,               //允许联网
            Manifest.permission.ACCESS_NETWORK_STATE,   //获取GSM（2g）、WCDMA（联通3g）等网络状态的信息
            Manifest.permission.ACCESS_WIFI_STATE,      //获取wifi网络状态的信息
            Manifest.permission.WAKE_LOCK,              //保持CPU 运转，屏幕和键盘灯有可能是关闭的,用于文件上传和下载
            Manifest.permission.WRITE_EXTERNAL_STORAGE, //获取sd卡写的权限，用于文件上传和下载
            Manifest.permission.READ_PHONE_STATE,       //允许读取手机状态 用于创建BmobInstallation
    })
    public void requestPermission() {
        //申请权限成功
        //Toast.makeText(this, "申请权限成功", Toast.LENGTH_SHORT).show();

    }

    /**
     * 只要有一个权限没有申请成功，且没有选择"以后不再询问"，则提示失败
     */
    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,               //允许联网
            Manifest.permission.ACCESS_NETWORK_STATE,   //获取GSM（2g）、WCDMA（联通3g）等网络状态的信息
            Manifest.permission.ACCESS_WIFI_STATE,      //获取wifi网络状态的信息
            Manifest.permission.WAKE_LOCK,              //保持CPU 运转，屏幕和键盘灯有可能是关闭的,用于文件上传和下载
            Manifest.permission.WRITE_EXTERNAL_STORAGE, //获取sd卡写的权限，用于文件上传和下载
            Manifest.permission.READ_PHONE_STATE,       //允许读取手机状态 用于创建BmobInstallation
    })
    public void requestPermissionDenied() {
        //申请权限失败
        //Toast.makeText(this, "申请权限失败", Toast.LENGTH_SHORT).show();
    }

    /**
     * 申请失败后，再申请则调用
     *
     * @param permissionRequest
     */
    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,               //允许联网
            Manifest.permission.ACCESS_NETWORK_STATE,   //获取GSM（2g）、WCDMA（联通3g）等网络状态的信息
            Manifest.permission.ACCESS_WIFI_STATE,      //获取wifi网络状态的信息
            Manifest.permission.WAKE_LOCK,              //保持CPU 运转，屏幕和键盘灯有可能是关闭的,用于文件上传和下载
            Manifest.permission.WRITE_EXTERNAL_STORAGE, //获取sd卡写的权限，用于文件上传和下载
            Manifest.permission.READ_PHONE_STATE,       //允许读取手机状态 用于创建BmobInstallation
    })
    public void requestPermissionShowRationale(final PermissionRequest permissionRequest) {
        new AlertDialog.Builder(this).setMessage("申请读取存储权限")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定后，则弹出申请权限的提示
                        permissionRequest.proceed();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//取消后，调用requestPermissionDenied
                        permissionRequest.cancel();
                    }
                }).show();
    }

    /**
     * 只要有一个申请失败，且选择了"以后不再询问"，则提示
     */
    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_CALENDAR})
    public void requestPermissionNeverAskAgain() {
        //Toast.makeText(this, "申请权限失败，且不再提示", Toast.LENGTH_SHORT).show();
    }
}
